import React from 'react';
import {Form, Input, Tooltip, Icon, Cascader, Select, Table, Upload, Checkbox, Button, Card , Breadcrumb , message} from 'antd';
import AppHelper from '../../../AppHelper';
import 'whatwg-fetch'
const FormItem = Form.Item;
const {TextArea} = Input

class BrandForm extends React.Component {

    constructor(props){
        super(props);
        this.uploadUrl = AppHelper.config.serviceUrl + '/brand/uploadLogo';
        this.deleteUrl = AppHelper.config.serviceUrl + '/brand/deleteLogo';
        this.createUrl = AppHelper.config.serviceUrl + '/brand';
    }
    state = {
        categories : []
    }

    componentDidMount () {
        let url = AppHelper.config.serviceUrl + '/categories'
        fetch(url)
        .then(res => res.json())
        .then((resp) => {
            let categories = AppHelper.tools.formatCategories(resp.data.categories);
            this.setState({categories});
        })
    }

    onParentChange () {
        console.info('parent changed');
    }

    handleLogoChange = (info) => {
        let fileList = info.fileList;
        fileList = fileList.slice(-1);
        this.setState({ fileList });
    }

    handleLogoRemove = (info) => {
        if(!info.response){
            return;
        }
        var data = {
            logoKey : info.response.data.fileKey
        }
        fetch(this.deleteUrl,{
            method : 'POST',
            headers : {
                'Accept' : 'application/json',
                'Content-Type' : 'application/json'
            },
            body : JSON.stringify(data)
        })
        .then(res => res.json());
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (err) {
                console.log('Received values of form: ', values);
                return;
            }

            let formVals = this.props.form.getFieldsValue();
            formVals.categoryId = formVals.categoryId.pop();
            if(formVals.upload && formVals.upload.file.response){
                formVals.logo = formVals.upload.file.response.data.fileKey;
                delete formVals.upload;
            }
            message.loading('保存中',0);
            fetch(this.createUrl , {
                method : 'POST',
                headers : {
                    'Accept' : 'application/json',
                    'Content-Type' : 'application/json'
                },
                body : JSON.stringify(formVals)
            }).then(res => res.json())
            .then((resp) => {
                message.destroy();
                window.location.hash='/app/brands'
            })
            .catch((error) => {
                message.destroy();
            })

            console.info(formVals)
        });
    }

    render() {
        const {getFieldDecorator} = this.props.form;

        const formItemLayout = {
            labelCol: {
                xs: {span: 20},
                sm: {span: 3},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 14},
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 14,
                    offset: 6,
                },
            },
        };

        return (
                <Form onSubmit={e => {this.handleSubmit(e)}}>
                    <FormItem {...formItemLayout} label="商品分类" >
                        {getFieldDecorator('categoryId', {
                            initialValue: ['1'],
                            rules: [{
                                type: 'array',
                                required: true,
                                message: '请选择商品分类!'
                            }],
                        })(
                            <Cascader options={this.state.categories} onChange={this.onParentChange} changeOnSelect/>
                        )}
                    </FormItem>
                    <FormItem {...formItemLayout} label="品牌名称" hasFeedback >
                        {getFieldDecorator('name', {
                            initialValue: this.props.data.name,
                            rules: [{required: true, message: '请填写品牌名称!', whitespace: true}],
                        })(
                            <Input/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="品牌logo"
                        extra="上传品牌logo图片"
                    >
                        {getFieldDecorator('upload')(
                            <Upload name="logo" 
                                    fileList={this.state.fileList} 
                                    withCredentials={true}
                                    action={this.uploadUrl} 
                                    listType="picture" 
                                    onChange={this.handleLogoChange}
                                    onRemove={this.handleLogoRemove}>
                                <Button>
                                    <Icon type="upload" />上传
                                </Button>
                            </Upload>
                        )}
                    </FormItem>
                    <FormItem {...formItemLayout} label="排序" hasFeedback>
                        {getFieldDecorator('orderNum', {initialValue: this.props.data.orderNum})(
                            <Input placeholder="根据排序进行由小到大排列显示" type="number"/>
                        )}
                    </FormItem>
                    <FormItem {...formItemLayout} label="是否为推荐品牌" hasFeedback>
                        {getFieldDecorator('recommended', {
                            valuePropName: 'checked',
                            initialValue: this.props.data.recommended,
                        })(
                            <Checkbox/>
                        )}
                    </FormItem>
                    <FormItem {...formItemLayout} label="品牌描述" hasFeedback>
                        {getFieldDecorator('description')(
                            <TextArea rows={4} placeholder="品牌描述信息"/>
                        )}
                    </FormItem>
                    <FormItem {...tailFormItemLayout}>
                        <Button type="primary" htmlType="submit" size="large">创建品牌</Button>
                    </FormItem>
                </Form>
        );
    }
}

const BrandFormPage = Form.create()(BrandForm);

export default BrandFormPage;